package com.qingke.besuper.command.impl;

import java.util.List;

import com.qingke.besuper.command.UserCommand;
import com.qingke.besuper.pojo.Answer;
import com.qingke.besuper.pojo.Question;
import com.qingke.besuper.pojo.User;
import com.qingke.besuper.util.BeSuperConsole;

public class ChooseBestAnswerCommand extends UserCommand implements ListAnswersByQuestionId{

	public ChooseBestAnswerCommand(User user) {
		super(user);
	}

	@Override
	public void execute() {
		String num=BeSuperConsole.promptNotEmpty("Please input question id:").trim();
		if(!num.replaceAll("[0-9]","").equals("")){
			BeSuperConsole.println("err input");
			return ;
		}
		int questionId=Integer.parseInt(num);
		Question question=dao.getQuestionByQuestionId(questionId);
		if(question.getPlayerId()!=this.user.getId()){
			BeSuperConsole.println("It's not your question.");
			return ;
		}
		
		List<Answer> arrA=dao.getAnswersByQuestionId(questionId);
		if(arrA.size()==0){
			BeSuperConsole.println("The question no answer.");
			return ;
		}
		
		ListAnswersByQuestionIdCommand(question.getId());
		BeSuperConsole.println();
		
//		BeSuperConsole.println("------the question------");
//		BeSuperConsole.println(q.getContext());
		
		String bestStr=BeSuperConsole.promptNotEmpty("input best answer's id:").trim();
		if(!bestStr.replaceAll("[0-9]","").equals("")){
			BeSuperConsole.println("err input");
			return ;
		}
		int newBest=Integer.parseInt(bestStr);
		int oldBest=question.getBestAnswerId();
		
		Answer newA=dao.getAnswerByAnswerId(newBest);
		Answer oldA=dao.getAnswerByAnswerId(oldBest);
		
		if(newA==null){
			BeSuperConsole.println("The answer is not exited.");
			return ;
		}
		
		if(!arrA.contains(newA)){
			BeSuperConsole.println("The answer you choose is not one of the question'answers.");
			return ;
		}
		
		if(newBest==oldBest){
			BeSuperConsole.println("The answer is already the best answer.");
			return ;
		}
		
		if(newA.getPlayerId()==user.getId()){
			BeSuperConsole.println("You can't choose the answer yourself.");
			return ;
		}
		
		int newId=-1;
		int oldId=-1;
		if(newA!=null){
			newId=newA.getId();
		}
		if(oldA!=null){
			oldId=oldA.getId();
		}
		
		int isSuccess=dao.updateScoreTwo(newId, oldId, questionId);
		if(isSuccess>0){
			BeSuperConsole.println("Choose the best answer success");
			return ;
		}
		BeSuperConsole.println("Choose the best answer failed");
		
	}

}
